import { useMemo } from 'react';
import {
  Modal,
  Form,
  Input,
  Radio,
  Space,
  Button,
  TreeSelect,
  Popover,
  InputNumber,
  Switch,
  Select,
  App,
} from 'antd';
import type { ModalProps } from 'antd';
import { SiConsul } from 'react-icons/si';
import { useEffect } from 'react';
import { MenuType } from 'src/constants';
import { IconPanel } from 'src/components/Icons';
import PermissionButton from 'src/components/Permission';
import { UpdateMenu, AddMenu } from 'src/api/modules/system';
import { IMenuHandleRequestData, IMenuRespFlatData } from 'src/interface';
import { useBoolean } from 'ahooks';

interface IProps extends ModalProps {
  data: IMenuRespFlatData | null;
  menuList: IMenuRespFlatData[] | null;
  onOk?: () => void;
  onCancel?: () => void;
}

export interface ISelectTree {
  label: string;
  value: string;
  children?: ISelectTree[];
}

export default function MenuModal(props: IProps) {
  const { data, menuList, onCancel, open, onOk, ...rest } = props;
  const [iconVisible, { setTrue, setFalse }] = useBoolean(false);
  const [loading, { toggle }] = useBoolean(false);
  const [formInstance] = Form.useForm();
  const menuType = Form.useWatch('menuType', formInstance);
  const { message } = App.useApp();

  const onSubmit = async () => {
    const result = await formInstance.validateFields();
    if (!result) return;
    const request = data ? UpdateMenu : AddMenu;
    toggle();
    const requestBody = { ...(data ?? {}), ...result } as IMenuHandleRequestData;
    requestBody.parentId = requestBody.parentId ?? -1;
    try {
      await request({
        ...requestBody,
        parentId: requestBody.parentId ?? -1,
      });
      onCancel && onCancel();
      onOk && onOk();
      message.success(`菜单${data ? '修改' : '新增'}成功`);
    } catch (err) {
      console.log(err);
    } finally {
      toggle();
    }
  };

  const menuTree = useMemo(() => {
    if (!menuList) return [];
    const transformData = (data: IMenuRespFlatData): ISelectTree => {
      return {
        value: data.menuId,
        label: data.name ?? '',
        children: data.children?.map(transformData),
      };
    };
    return menuList.map((item) => transformData(item));
  }, [menuList]);

  useEffect(() => {
    if (!open) return;
    if (data) {
      formInstance.setFieldsValue(data);
    } else {
      formInstance.resetFields();
      formInstance.setFieldValue('menuType', MenuType[0].value);
    }
  }, [open, data, formInstance]);

  return (
    <Modal
      open={open}
      {...rest}
      title={`${data ? '编辑' : '新增'}菜单`}
      footer={null}
      onCancel={onCancel}>
      <Form form={formInstance} layout="horizontal" labelCol={{ span: 5 }}>
        <Form.Item name="menuType" label="菜单类型">
          <Radio.Group buttonStyle="solid" disabled={!!data}>
            {MenuType.map((item) => {
              return (
                <Radio.Button key={item.value} value={item.value}>
                  {item.label}
                </Radio.Button>
              );
            })}
          </Radio.Group>
        </Form.Item>
        {menuType !== MenuType[0].value && (
          <Form.Item
            name="parentId"
            label="父级菜单"
            required
            rules={[{ required: true, message: '请选择父级菜单' }]}>
            <TreeSelect treeData={menuTree} placeholder="请选择父级菜单"></TreeSelect>
          </Form.Item>
        )}
        <Form.Item
          name="name"
          label="菜单名称"
          required
          rules={[{ required: true, message: '请输入菜单名称' }]}>
          <Input placeholder="请输入菜单名称" autoComplete="off" />
        </Form.Item>
        {menuType !== MenuType[2].value && (
          <Form.Item
            name="path"
            label="菜单路径"
            required
            rules={[{ required: true, message: '请输入菜单路径' }]}>
            <Input placeholder="请输入菜单路径" autoComplete="off" />
          </Form.Item>
        )}
        {menuType === MenuType[2].value && (
          <Form.Item
            name="permission"
            label="权限标识"
            required
            rules={[{ required: true, message: '请输入权限标识' }]}>
            <Input placeholder="请输入权限标识" autoComplete="off" />
          </Form.Item>
        )}
        {menuType !== MenuType[2].value && (
          <Form.Item name="icon" label="菜单图标">
            <Input
              placeholder="请输入菜单图标"
              autoComplete="off"
              onFocus={(e) => {
                e.stopPropagation();
                setTrue();
              }}
              addonAfter={
                <Popover
                  open={iconVisible}
                  onOpenChange={(value) => {
                    value ? setTrue() : setFalse();
                  }}
                  content={
                    <IconPanel
                      onSelect={(value) => {
                        formInstance.setFieldValue('icon', value);
                        setFalse();
                      }}
                    />
                  }>
                  <SiConsul />
                </Popover>
              }
            />
          </Form.Item>
        )}
        {menuType !== MenuType[2].value && (
          <Form.Item name="locale" label="多语言Key">
            <Input placeholder="请输入" autoComplete="off" />
          </Form.Item>
        )}
        <Form.Item name="visible" label="是否显示">
          <Switch />
        </Form.Item>
        <Form.Item
          name="sortOrder"
          label="排序值"
          required
          rules={[{ required: true, message: '请输入排序值' }]}>
          <InputNumber placeholder="请输入" autoComplete="off" />
        </Form.Item>
        {menuType !== MenuType[2].value && (
          <Form.Item
            name="target"
            label="外链类型"
            extra={'注意：选择外链类型后，标识该菜单为外链'}>
            <Select options={MenuType} placeholder="请选择外链类型"></Select>
          </Form.Item>
        )}
      </Form>
      <div className="flex justify-end">
        {
          <Space>
            <Button disabled={loading} onClick={onCancel}>
              取消
            </Button>
            <PermissionButton
              permission={data ? 'SYSTEM_MENU_EDIT' : 'SYSTEM_MENU_ADD'}
              loading={loading}
              type="primary"
              onClick={onSubmit}>
              保存
            </PermissionButton>
          </Space>
        }
      </div>
    </Modal>
  );
}
